<?php
class adminModel extends RelationModel
{
    protected $_validate = array(
        array('userName', 'require', '{%admin_userName_empty}'), //不能为空
        array('userName', '', '{%admin_name_exists}', 0, 'unique', 1), //新增的时候检测重复
    );
  
    
    public function _initialize()
    {
        parent::_initialize();       
    }    
   

    protected $_link = array(
        //关联角色
        'role' => array(
            'mapping_type' => BELONGS_TO,
            'class_name' => 'admin_role',
            'foreign_key' => 'roleId',
        )
    );

    /*
     * 检测名称是否存在
     *
     * @param string $name
     * @param int $id
     * @return bool
     */
    public function name_exists($name, $id=0) {
        $pk = $this->getPk();
        $where = "userName='" . $name . "'  AND ". $pk ."<>'" . $id . "'";
        $result = $this->where($where)->count($pk);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    
    
    
    /**
     * 
     */ 
    protected function _after_insert($data,$option){
        $admin = session('admin');
        $imeiInfo = M('pad_imei')->where(array('imei'=>$data['imei']))->find();        
        $imeiInfo['ophistory'] = empty($imeiInfo['ophistory'])?'':$imeiInfo['ophistory'];
        $dateImei['imei'] = $data['imei'];    
        $str = '';
        if($imeiInfo['userId']){
           $oldUserinfo = M('admin')->where(array('id'=>$imeiInfo['userId']))->find();
           $str .=$admin['userName'].'从'.$oldUserinfo['userName'].'手中收回，并重新发放给'.$data['userName']; 
        }else{
            $str .=$admin['userName'].'发放给'.$data['userName'];
        }  
        $dateImei['ophistory'] = $imeiInfo['ophistory']."\n".$str;
        $dateImei['userId'] = $data['id'];
        M('pad_imei')->where(array('imei'=>$data['imei']))->save($dateImei);
        
        $simInfo = M('pad_sim')->where(array('sim'=>$data['sim'],'simSn'=>$data['simSn']))->find();        
        $simInfo['ophistory'] = empty($simInfo['ophistory'])?'':$simInfo['ophistory'];
        $dateSim['sim']   = $data['sim'];    
        $dateSim['sim_sn'] = $data['simSn']; 
        $str = '';
        if($simInfo['userId']){
           $oldUserinfo = M('admin')->where(array('id'=>$imeiInfo['userId']))->find();
           $str  .=$admin['userName'].'从'.$oldUserinfo['userName'].'手中收回，并重新发放给'.$data['userName']; 
        }else{
            $str .=$admin['userName'].'发放给'.$data['userName'];
        }   
        $dateSim['ophistory'] = $simInfo['ophistory']."\n".$str;
        $dateSim['userId'] = $data['id'];
        M('pad_sim')->where(array('sim'=>$data['sim']))->save($dateSim);       
    }

    /**
	 * 根据用户id获得用户的详细信息
	 */
	public function get_user_info($id){
        //取到账号信息，角色信息，厅店信息
		$field = array(
			'admin.username',
			'admin.realName',
			'admin.roleId',
			'admin.phone',
			'admin.company',
			'admin.jobPost',
			'admin.sim',
			'admin.simSn',
			'admin.imei',
			'admin.storeId',
            'admin.regionId',
            'admin.id'=>'id',
            //'admin.customerIds'=>'customerIds',
            'role.regionLevel'=>'roleLevel',
            'role.name'=>'roleName',
			'store.name' => 'storeName',
            'store.ctms'=>'ctms',
            'store.regionId'=>'storeRegionId',
            'store.gps'=>'storeGps',
            //'store.positionY'=>'storePositionY',
            'store.address'=>'storeAddress',
            //'store.channel'=>'storeChannel',
            'store.bcId'=>'storeBcId',
            //'store.customerId'=>'storeCustomerId',  //客户ID
		);
		$res = $this->alias('admin')->field($field)
				->join(C('DB_PREFIX')."store AS store ON store.id = admin.storeId")
				->join(C('DB_PREFIX')."admin_role AS role ON role.id = admin.roleId")
				->where(array('admin.id'=>$id,'admin.status'=>1,'role.status'=>1))
				->find();
                
        //取子地区
        $regionId = $res['regionId'];
        if(!empty($res['storeRegionId'])){  // 从厅店的片区ID开始找
            $regionId = $res['storeRegionId'];
        }
    
        $regionModel = D('region');

        //$res['regionIds'] 保存着所有有权限的地区ID
        
        $regionList = $regionModel->cate_cache();
        $spid = $regionList['l'][$regionId]['spid'];
         
        if(!empty($regionId)){
            $spid = trim($spid,'|');       
            $spidArr = explode('|',$spid);   
            $levelArr = C('LEVEL_ARR');
            $res['regionIds'][] = $regionId;  
            $res[$levelArr[$regionList['l'][$regionId]['level']]['title']][] = $regionId;                            
           //循环所有等级
            foreach($levelArr as $k=>$v){ 
                $title = $v['title'];
                $beforeTitle = $levelArr[$k-1]['title'];
                // 这个等级存在              
                if(isset($spidArr[$k]) && !empty($spidArr[$k]) ){
                    $res[$title][] = $spidArr[$k];
                    $res['regionIds'][] = $spidArr[$k];
                }elseif(empty($res[$title])){
                    $pidArr = array();
                    if(!is_array($res[$beforeTitle])){
                        $pidArr[] = intval($res[$beforeTitle]);
                    }else{
                        foreach($res[$beforeTitle] as $bk=>$bv){
                           $pidArr[] = $bv; 
                        }
                    }
                    $res[$title] = array();
                    foreach($pidArr as $pid){
                        foreach($regionList['s'][$pid] as $rk=>$rv){
                            $res[$title][] = $rv['id'];
                            $res['regionIds'][] = $rv['id'];
                        }
                    }
                }
            }
        }       
        //找下属
		$field = array(
			'admin.id',
            'admin.userName',
		);
		$underList = $this->alias('admin')->field($field)
				->join(C('DB_PREFIX')."admin_role AS role ON role.id = admin.roleId")
				->where(array('role.pid'=>$res['roleId'],'admin.status'=>1,'role.status'=>1))
				->select();        
        $res['underList'] = $underList;
        if($underList){
            foreach($underList as $v){
                $res['underListIds'][] = $v['id'];
            }
        }
		return $res;
	}
    
	
	/**
	 * 获得我的下属员工的用户id列表，用 “,” 分隔
	 */
	public function get_subordinate_ids(){
		$ids	= '';
		$user	= getUserSession();
		$subRoleId	= '';	//下级的角色id
		$subRegionId= '';	//下级的地区id
		
		//排除促销员和销售代表
		if($user['roleLevel'] < 3){
			//获得下属角色
			$subRoles = D('adminRole')->where(array('regionLevel'=>++$user['roleLevel']))->select();
			foreach ($subRoles as $sub){
				$subRoleId .= $sub['id'].',';
			}
			$subRoleId = trim($subRoleId, ',');
			
			//获得下属地区
			if($user['roleLevel'] < 2 && $subRegion = D('Region')->where(array('pid'=>$user['regionId'], 'status'=>1))->select()){
				foreach ($subRegion as $r){
					$subRegionId .= $r['id'].',';
				}
				$subRegionId = rtrim($subRegionId, ',');
			}else{
				$subRegionId = $user['regionId'];
			}
			
			if($subRoleId && $subRegionId){
				$res = D('admin')->field('id')->where("roleId IN ({$subRoleId}) AND regionId IN ({$subRegionId})")->select();
				if($res){
					foreach ($res as $row){
						$ids .= $row['id'].',';
					}
					$ids = rtrim($ids, ',');
				}
			}
		}
		return $ids;
	}
	
	/**
	 * 获得用户头像
	 */
	public function getIcon($userId){
		$res = $this->alias('admin')->field("role.img")
		->join(C('DB_PREFIX')."admin_role AS role ON role.id = admin.roleId")
		->where(array('admin.id'=>$userId))
		->cache(600)->find();  
		if($res && $res['img']){
			$icon = __ROOT__.C('pin_attach_path').'admin_role/'.$res['img'];
			}else{
			$icon = __ROOT__.C('pin_attach_path').'user/icon/default.jpg'; //用户头像
		}
		return $icon;
	}

    protected function _after_update($data,$options)
    {
        
        $data = D('userHistory')->create($_REQUEST);
        $data['userId'] = intval($_REQUEST['id']);
        D('userHistory')->add($data);
        
        $data = D('userTrain')->create($_REQUEST);
        $data['userId'] = intval($_REQUEST['id']);
        D('userTrain')->add($data);
    }
    
}